#https://medium.com/@gratefulcheddar/rubygems-101-how-to-use-a-third-party-gem-in-your-ruby-application-37249529dbc7

#knitpattern.rb FUNCTIONS WELL
# This is a refactor

require 'tty-prompt'
require 'tty-screen'
require 'pastel'
require 'tty-cursor'
require 'tty-font'


# TITLE SCREEN #



@pastel   = Pastel.new
@cursor   = TTY::Cursor
@font     = TTY::Font.new(:doom)
@reg_font = TTY::Font.new(:straight)


	def lines_at(lines, x, y)

	  lines.each_with_index.reduce([]) do |acc, (line, i)|
		acc << @cursor.move_to(x - line.size/2, y - lines.size/2 + i) + line
		acc
	  end

	end

	@size = TTY::Screen.size

		center_x = @size[1]/2
		center_y = @size[0]/2
		
  print @cursor.save
  print @cursor.clear_screen
  print @cursor.hide
		
 

  lines = @font.write('GRADIENT').split("\n")
  print @pastel.bright_red(lines_at(lines, center_x, center_y - 3).join)
  lines = @font.write('MAKER').split("\n")
  print @pastel.red(lines_at(lines, center_x, center_y + 3).join)

print "\n\n"
@cursor.next_line

picarray = [
			["□","□","□","□","□","□","□","□","□","□"],
			["□","□","□","■","□","□","□","□","■","□"],
			["□","□","■","□","■","□","□","■","□","■"],
			["■","□","■","■","□","■","□","■","■","□"],
			["■","□","■","■","■","■","□","■","■","■"],
			["■","■","■","■","■","■","■","■","■","■"]
]
#=begin
picarray.each {|rw|
	rw.each {|cell|
	print cell
	}
	print "\n"
}
#=end

print "press ENTER to continue"

gets


# INTRODUCTION #

print "\n\n This program makes a grid of squares, gradually changing from one colour to another. You can use this pattern for cross stitch, knitting, or any other craft. The pattern will be a .csv file, which you can open in Excel or any other spreadsheet program."

print "\n\n >> For row and stitch numbers, just type a number ('40' not '40 rows' or 'forty')."
print "\n\n >> For Output File, type a word and do not use any punctuation. The file will overwrite any other files with this name in the folder, so doublecheck before you run the program. The finished file will be saved in the same folder as the gradientmaker.rb program".center(10)

print "\n\n Answer each question, then press ENTER to continue. \n\n".center(10)

# TAKE INPUTS #

require "tty-prompt"

	prompt = TTY::Prompt.new

checker = false

until checker == true
	result = prompt.collect do

  key(:name).ask("1. Name your output file") do |q|
	
	q.modify :chomp
	
	q.required true
	
	q.validate(/[a-zA-Z]/)
	
	q.messages[:valid?] = "Please only use letters (lowercase and uppercase a-z and/or A-Z)"
	
	q.convert -> (input) { input << '.csv' }
	
	
  end

  print "\n"
	
  key(:row).ask("2. How many rows heigh is the gradient section?") do |q|
	
	q.convert :int
	
	q.messages[:convert?] = "That isn't a number. Please type in a number in digits, i.e. '30', with no words or punctuation"
	
	q.modify :chomp
	
	q.required true
	
  end

  print "\n"

  key(:stitch).ask("3. How many stitches per row wide is the gradient section?") do |q|
  
    q.convert :int
	
	q.messages[:convert?] = "That isn't a number. Please type in a number in digits, i.e. '30', with no words or punctuation"
	
	q.modify :chomp
	
	q.required true
	
  end
  
end

	print "\n \n"
	print "You are about to create a new file called #{result[:name]}, containing a pattern #{result[:row]} rows heigh and #{result[:stitch]} stitches wide."
	print "\n \n"

	checker = prompt.yes?("Is this correct?")
end



=begin


1.upto(100) do |i|
  printf("\rProcessing: %d%%", i)
  sleep(0.05)
end
=end

print "\n \n  [ COMPLETE! ]"

print "\n\n Open your new file ( #{result[:name]}) and see if the pattern is correct! Then save it in a different format (.xls, .ods etc) to add conditional formatting (which will automatically adds the two different colour backgrounds to the cells) change the column and row heights to look square, and add any more details. If it doesn't look quite right, then run the program again with new numbers."

print "\n\n"
print "\n\n"

# Make an array to hold the pattern

	pattern = Array.new(result[:row]) {Array.new}

# Calculate the pattern

	pattern.each_index {|i|

						#puts "ROW #{i}/#{pattern.count}"

	#what percentage of the way through the rows are we?
	
		rw = i + 1
	
		perc = rw.to_f/result[:row].to_f
	
	#this is also the percentage of stitches that are black on this row; 
					# i.e. 25% down the gradient, 25% of the stitches are black. 
					# 100% down the gradient, 100% of the stitches are black
	
	# if perc goes above 1, or is a negative number, there will be an error
	
		if perc > 1.0 or perc < 0.0
			puts "ERROR: perc is #{perc}"
			gets
		end
		
									#puts "perc is #{perc}, a #{perc.class}"
									#gets
	
	black = result[:stitch] * perc
	
	black = black.round				#stitches must be a whole number
		
									#puts "black = #{black}"
		
	white = result[:stitch] - black
	
									#puts "white = #{white}"
		
	pattern[i] << '■' * black
	pattern[i] << '□' * white
	
}

# join into a single string, i guess

	pattern.each {|rw|

	rw[0] << rw[1]
	rw.delete_at(1)
}


# shuffle time, and deal with the doublearray issue created

	def string_shuffle(s)
	
		s.split("").shuffle!
		
	end

	pattern.each {|rw|

		rw[0] = string_shuffle(rw[0])
		rw.flatten!
	}

# OPTIONALLY
# Add a Row Number to the beginning of each row
# Add a Row at the top counting stitch numbers for you also


# write to csv

	require "csv"
	File.write(result[:name], pattern.map(&:to_csv).join)


#TEST
##A square		YES

##Rectangle: longer than wide	ALL YES
	# both numbers even			
	# both numbers odd			
	# A odd, B even				
	# A even, B odd				
	
##Rectangle: wider than long	ALL YES
	# both numbers even
	# both numbers odd
	# A odd, B even
	# A even, B odd
	
# Catch wrong number inputs


# NOW OPEN IN EXCEL - ADD CONDITIONAL FORMATTING

# 0. highlight and copy the white square
# 1. highlight whole document
# 2. go to conditional formatting
# 3. paste white square, and choose a colour
# 4. document will now show colours graphically
# 5. repeat with black square
# 6. save file as a different format (NOT a .csv)

 